package com.xuhao.examai.scoring.application.services.impl;

import com.xuhao.examai.scoring.application.services.ScoringService;
import com.xuhao.examai.scoring.application.dto.ExamStatistics;
import com.xuhao.examai.scoring.domain.models.AnswerRecord;
import com.xuhao.examai.scoring.domain.models.ExamRecord;
import com.xuhao.examai.scoring.domain.repositories.AnswerRecordRepository;
import com.xuhao.examai.scoring.domain.repositories.ExamRecordRepository;
import com.xuhao.examai.common.PageResult;
import com.xuhao.examai.exception.BusinessException;
import com.xuhao.examai.exception.NotFoundException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class ScoringServiceImpl implements ScoringService {

	private final ExamRecordRepository examRecordRepository;
	private final AnswerRecordRepository answerRecordRepository;

	@Override
	public AnswerRecord scoreAnswer(Long examRecordId, Long questionId, String studentAnswer) {
		log.info("评分单个答案: examRecordId={}, questionId={}", examRecordId, questionId);

		// 获取考试记录
		ExamRecord examRecord = getExamRecord(examRecordId);

		// 创建或更新答案记录
		AnswerRecord answerRecord = answerRecordRepository.findByExamRecordIdAndQuestionId(examRecordId, questionId)
				.orElse(new AnswerRecord());

		answerRecord.setExamRecordId(examRecordId);
		answerRecord.setQuestionId(questionId);
		answerRecord.setStudentAnswer(studentAnswer);

		// TODO: 从question-service获取正确答案和分值
		// 这里需要调用question-service的API或通过消息队列获取
		// 暂时使用模拟数据
		answerRecord.setCorrectAnswer("模拟正确答案");
		answerRecord.setMaxScore(10);

		// 计算得分
		answerRecord.calculateScore();

		// 保存答案记录
		return answerRecordRepository.save(answerRecord);
	}

	@Override
	public List<AnswerRecord> batchScoreAnswers(Long examRecordId, List<AnswerRecord> answerRecords) {
		log.info("批量评分答案: examRecordId={}, count={}", examRecordId, answerRecords.size());

		return answerRecords.stream()
				.map(record -> {
					record.setExamRecordId(examRecordId);
					record.calculateScore();
					return answerRecordRepository.save(record);
				})
				.collect(Collectors.toList());
	}

	@Override
	public ExamRecord completeExamScoring(Long examRecordId) {
		log.info("完成考试评分: examRecordId={}", examRecordId);

		ExamRecord examRecord = getExamRecord(examRecordId);

		// 获取所有答案记录
		List<AnswerRecord> answerRecords = getAnswerRecords(examRecordId);

		// 计算总分
		examRecord.setAnswerRecords(answerRecords);
		examRecord.calculateTotalScore();

		// 完成评分
		examRecord.completeScoring();

		return examRecordRepository.save(examRecord);
	}

	@Override
	@Transactional(readOnly = true)
	public ExamRecord getExamRecord(Long examRecordId) {
		log.info("获取考试记录: examRecordId={}", examRecordId);

		return examRecordRepository.findById(examRecordId)
				.orElseThrow(() -> new NotFoundException("考试记录", examRecordId.toString()));
	}

	@Override
	@Transactional(readOnly = true)
	public List<AnswerRecord> getAnswerRecords(Long examRecordId) {
		log.info("获取答案记录列表: examRecordId={}", examRecordId);
		return answerRecordRepository.findByExamRecordId(examRecordId);
	}

	@Override
	@Transactional(readOnly = true)
	public List<ExamRecord> getStudentExamRecords(Long studentId) {
		log.info("获取学生考试记录: studentId={}", studentId);
		return examRecordRepository.findByStudentId(studentId);
	}

	@Override
	@Transactional(readOnly = true)
	public PageResult<ExamRecord> getExamRecordsByPage(Integer current, Integer size, Long examId, Long studentId,
			String status) {
		log.info("分页查询考试记录: current={}, size={}, examId={}, studentId={}, status={}",
				current, size, examId, studentId, status);

		// TODO: 实现分页查询逻辑
		List<ExamRecord> records = examRecordRepository.findByExamId(examId);
		return PageResult.of(records, (long) records.size(), current, size);
	}

	@Override
	@Transactional(readOnly = true)
	public ExamStatistics getExamStatistics(Long examId) {
		log.info("获取考试统计信息: examId={}", examId);

		List<ExamRecord> examRecords = examRecordRepository.findByExamId(examId);

		ExamStatistics statistics = new ExamStatistics();
		statistics.setExamId(examId);
		statistics.setTotalStudents(examRecords.size());

		// 计算提交和评分数量
		long submittedCount = examRecords.stream()
				.filter(record -> "submitted".equals(record.getStatus()) || "scored".equals(record.getStatus()))
				.count();
		statistics.setSubmittedCount((int) submittedCount);

		long scoredCount = examRecords.stream()
				.filter(record -> "scored".equals(record.getStatus()))
				.count();
		statistics.setScoredCount((int) scoredCount);

		// 计算平均分、最高分、最低分
		List<ExamRecord> scoredRecords = examRecords.stream()
				.filter(record -> "scored".equals(record.getStatus()) && record.getTotalScore() != null)
				.collect(Collectors.toList());

		if (!scoredRecords.isEmpty()) {
			double averageScore = scoredRecords.stream()
					.mapToInt(ExamRecord::getTotalScore)
					.average()
					.orElse(0.0);
			statistics.setAverageScore(averageScore);

			double maxScore = scoredRecords.stream()
					.mapToInt(ExamRecord::getTotalScore)
					.max()
					.orElse(0);
			statistics.setMaxScore(maxScore);

			double minScore = scoredRecords.stream()
					.mapToInt(ExamRecord::getTotalScore)
					.min()
					.orElse(0);
			statistics.setMinScore(minScore);

			// 计算及格率等
			long passCount = scoredRecords.stream()
					.filter(record -> record.getScoreRate() >= 0.6)
					.count();
			statistics.setPassRate((double) passCount / scoredRecords.size());
		}

		return statistics;
	}

	@Override
	public ExamRecord rescoreExam(Long examRecordId) {
		log.info("重新评分考试: examRecordId={}", examRecordId);

		// 获取考试记录
		ExamRecord examRecord = getExamRecord(examRecordId);

		// 重新评分所有答案
		List<AnswerRecord> answerRecords = getAnswerRecords(examRecordId);
		for (AnswerRecord record : answerRecords) {
			record.calculateScore();
			answerRecordRepository.save(record);
		}

		// 重新计算总分
		examRecord.setAnswerRecords(answerRecords);
		examRecord.calculateTotalScore();

		return examRecordRepository.save(examRecord);
	}

	@Override
	public byte[] exportScoreReport(Long examRecordId) {
		log.info("导出成绩报告: examRecordId={}", examRecordId);

		ExamRecord examRecord = getExamRecord(examRecordId);
		List<AnswerRecord> answerRecords = getAnswerRecords(examRecordId);

		// TODO: 实现成绩报告导出逻辑
		// 这里可以生成PDF或Excel格式的报告
		String reportContent = generateReportContent(examRecord, answerRecords);

		return reportContent.getBytes();
	}

	/**
	 * 生成报告内容
	 */
	private String generateReportContent(ExamRecord examRecord, List<AnswerRecord> answerRecords) {
		StringBuilder content = new StringBuilder();
		content.append("考试记录ID: ").append(examRecord.getId()).append("\n");
		content.append("学生ID: ").append(examRecord.getStudentId()).append("\n");
		content.append("总分: ").append(examRecord.getTotalScore()).append("/").append(examRecord.getMaxScore())
				.append("\n");
		content.append("得分率: ").append(String.format("%.2f%%", examRecord.getScoreRate() * 100)).append("\n");
		content.append("状态: ").append(examRecord.getStatus()).append("\n");
		content.append("开始时间: ").append(examRecord.getStartTime()).append("\n");
		content.append("结束时间: ").append(examRecord.getEndTime()).append("\n");

		content.append("\n详细答题情况:\n");
		for (AnswerRecord record : answerRecords) {
			content.append("题目ID: ").append(record.getQuestionId()).append("\n");
			content.append("学生答案: ").append(record.getStudentAnswer()).append("\n");
			content.append("正确答案: ").append(record.getCorrectAnswer()).append("\n");
			content.append("得分: ").append(record.getScore()).append("/").append(record.getMaxScore()).append("\n");
			content.append("是否正确: ").append(record.getIsCorrect() ? "是" : "否").append("\n");
			content.append("---\n");
		}

		return content.toString();
	}
}